import { Bitmap } from '../models';
import { errorBase64Url } from '../utils/image';
import { isCanvasNode } from '../utils/nodeType';

/**
 * 将Canvas 解析为图片
 * @param canvas
 */
export const parseCanvasToBitmap = (canvas: HTMLCanvasElement) => {
  if (!isCanvasNode(canvas)) return;
  const { width, height, y, x } = canvas.getBoundingClientRect();
  let url;
  try {
    url = canvas.toDataURL();
  } catch (e) {
    const errMsg = (e as Error).toString();

    // 存在跨域问题
    if (errMsg.includes('Tainted canvases may not be exported.')) {
      // 跨域问题的显示图片
      url =
        '';
    } else url = errorBase64Url;
  }

  const bitmap = new Bitmap({ url, width, height, y, x });
  bitmap.mapBasicInfo(canvas);

  return bitmap;
};
